let animating = false; // 是否有窗口在动画中，是的画 禁止点击
let rightDivShown = false; // 右边窗口是否打开
let rightDivCode = ''; // 当前打开的船 编号
let middleDivShown = false; // 中间窗口是否打开
let middleRouteCode = '' // 中间的轨迹窗口编号
let middleDontFollowRight = false; // 这个变量用于再right切换数据的时候 middle就不需要跟着变了
let mapControllerAnimateWithRightDiv = false; // 这个变量是个配置
let animateTime = {
    right: 200,
    middle: 150,
    boatInfo: 150,
    button: 200,
}; // 动画时间

let player; // xgplayer

let rightDiv = $('.right');
let middleDiv = $('.middle');
let boatInfoDiv = $('.boat-info');

let intervalWidth = 10;
let headDivHeight = 50;
let leftDivWidth = 200;
let rightDivWidth = 400;


document.documentElement.style.setProperty('--interval-width', intervalWidth + 'px');
document.documentElement.style.setProperty('--left-div-width', leftDivWidth + 'px');
document.documentElement.style.setProperty('--right-div-width', rightDivWidth + 'px');
document.documentElement.style.setProperty('--head-div-height', headDivHeight + 'px');

// rightDiv 默认隐藏 不然刷出来的一瞬间会出现
rightDiv.css({'right': -(rightDivWidth + intervalWidth) + 'px'})
rightDiv.css('display', 'block')

// 如果窗口高度不够 就把视频先隐藏了
// if ($('body').height() < 1080) $('#load-panel').hide();

// 右侧窗口动画
function toggleRightDiv(info, show, callback) {
    animating = true;
    rightDiv.animate({right: !show ? -rightDiv.width() + 'px' : intervalWidth + 'px'}, animateTime.right, 'swing', callback);
    if (mapControllerAnimateWithRightDiv) $('.ol-popup').animate({right: !show ? intervalWidth + 'px' : rightDiv.width() + 2 * intervalWidth + 'px'}, animateTime.right, 'swing');
    if (!middleDontFollowRight) middleDiv.animate({width: !show ? middleDiv.width() + rightDivWidth + intervalWidth + 'px' : middleDiv.width() - rightDivWidth - intervalWidth + 'px'}, 200, 'swing');
}

function showLeftSubMenu(code) {
    var li = $(`#nav > li[data-code=${code}]`)
    if (!li.hasClass("opened")) li.click();
}

function showRightDiv(code) {
    // hideBoatInfo()
    if (rightDivCode === code) return;

    let boat = getBoatByCode(code)
    if (boat == null) return

    if (rightDivShown) {
        hideRightDiv(() => {
            showRightDiv(code)
        })
    } else { // 没有打开的情况下 更换数据 然后打开
        rightDivCode = code;
        hideLoadPanel();
        if (boat.statusList.length === 0) {
            return layer.msg('暂无状态数据', {icon: 7})
        }
        setStatus(boat)
        toggleRightDiv(boat, true, () => {
            animating = false;
            rightDivShown = true;
            middleDontFollowRight = false;
        })
    }

    boatPointSource.forEachFeature(function (feature) {
            if (feature.getProperties().code === code) {
                selectedBoatFeature = feature;
                selectedBoatFeature.setStyle(createBoatFeatureStyle(selectedBoatFeature, zoomLevel, true));
                return true;
            }
        }
    );
}

/**
 *
 * @param callback
 * @param fromCloseBtn
 */
function hideRightDiv(callback, fromCloseBtn = false) {
    if (selectedBoatFeature != null) {
        //非选中状态
        selectedBoatFeature.setStyle(createBoatFeatureStyle(selectedBoatFeature, zoomLevel));
    }
    if (!rightDivShown) return
    if (!fromCloseBtn && middleDivShown) middleDontFollowRight = true; // 不是按钮关闭，而是来自菜单选择， right隐藏的时候 发现middle开着 那么middle的尺寸就不用变了
    toggleRightDiv(null, false, () => {
        animating = false
        rightDivShown = false
        rightDivCode = ''
        if (callback) callback()
    })
}


// 中间窗口
window.addEventListener('resize', () => {
    middleDiv.width($(window).width() - leftDivWidth - intervalWidth - intervalWidth - (rightDivShown ? rightDivWidth + intervalWidth : 0))
});

/**
 * 打开中间窗口
 * @param title 标题
 * @param url iframe的url
 * @param mode 0 设备 1 轨迹
 */
function showMiddle(title, url, mode) {
    // hideBoatInfo()
    if (!mode) middleRouteCode = '';

    if (middleDivShown) { // 已打开就先关闭
        hideMiddle(false, () => {
            showMiddle(title, url, mode);
        });
    } else {
        $('.middle>.content>iframe').attr('src', url);
        $('.middle>.row>.title>span').html(title)
        $('.middle>.row>.title>i').attr('class', mode ? 'fa fa-map-o' : 'fa fa-desktop');
        animating = true;
        middleDiv.fadeIn(animateTime.middle, () => {
            animating = false;
            middleDivShown = true;
        })
    }

}

function hideMiddle(fromClose = false, callback) {
    middleRouteCode = '';
    animating = true;
    if (fromClose) $('.left-nav a.selected').removeClass('selected');
    middleDiv.fadeOut(animateTime.middle, () => {
        animating = false;
        middleDivShown = false;
        if (callback) callback()
    })
}

// 下拉菜单
$('.dropdown-menu').parent().hover(function () {
    $(this).find('.dropdown-menu').css('display', 'block')
}, function () {
    $(this).find('.dropdown-menu').css('display', 'none')
})

//左侧菜单效果

/**
 * 注册ui的点击事件
 */
function registerNavEvent() {
    // 波浪艇菜单动画
    $('.left-nav #nav li').click(function (event) {

        if (animating) return

        if ($(this).children('.sub-menu').length) {
            let code = $(this).data("code")
            if ($(this).hasClass('opened')) { // 如果已经打开 就关闭

                if (rightDivShown) { // 如果右边窗口打开着 就一起关闭了
                    $(this).removeClass('opened');

                    $(this).children('.sub-menu').stop().slideUp();
                    $(this).siblings().children('.sub-menu').slideUp();

                    // 改变右边箭头
                    $(this).find('i.fa').removeClass('fa-angle-down');
                    $(this).find('i.fa').addClass('fa-angle-left');

                    // 去掉选择了的设备
                    $('.left-nav .selected').removeClass('selected');
                    hideRightDiv();
                    hideMiddle()
                } else { // 右边窗口没有开 就打开
                    showRightDiv(code);
                    mapPanTo(code);
                }

            } else { // 没有打开 就打开 关闭其他的
                $(this).addClass('opened');
                $(this).siblings().removeClass('opened');

                $(this).siblings().children('.sub-menu').stop().slideUp();

                $(this).children('.sub-menu').stop().slideDown();

                // 改变右边箭头
                $(this).find('i.fa').removeClass('fa-angle-left');
                $(this).find('i.fa').addClass('fa-angle-down');

                // 改变其他节点的右边箭头
                $(this).siblings().find('i.fa').removeClass('fa-angle-down');
                $(this).siblings().find('i.fa').addClass('fa-angle-left');

                showRightDiv(code)
                mapPanTo(code) // 地图居中到该站点
            }
        }

        event.stopPropagation();

    })


    // 设备按钮动画
    $('.left-nav #nav li ul li a').click(function () {
        if ($(this).hasClass('selected')) {
            // $(this).removeClass('selected') // 再次点击的动作
        } else {
            $('#nav').find('li').each(function () {
                $(this).find('ul').find('li').each(function () {
                    $(this).find('a').removeClass('selected');
                })
            })
            $(this).addClass('selected')
            let url = $(this).attr('_href')
            let deviceName = $(this).data('name')
            let boatId = $(this).parent().parent().parent().data('id')
            let boatCode = $(this).parent().parent().parent().data('code')
            let boatName = $(this).parent().parent().parent().data('name')
            let deviceType = $(this).data('type')

            let finalUrl = `${url}?boatId=${boatId}&deviceType=${deviceType}`
            showMiddle(`${boatName} ${boatCode} ${deviceName}`, finalUrl, 0)
        }
    })

}

/**
 * 关闭子菜单
 */
function hideSubMenu() {
    $('.sub-menu').parent().removeClass('opened')
    $('.sub-menu').slideUp();
    $('.sub-menu').parent().siblings().find('i.fa').removeClass('fa-angle-down');
    $('.sub-menu').parent().siblings().find('i.fa').addClass('fa-angle-left');

    $('.left-nav #nav li ul li a').each(function () {
        $(this).removeClass('selected');
    })

    hideMiddle();
    hideRightDiv();
}

// 搜索栏
$('.left-nav .search').keydown(function (event) {
    if (event.keyCode === 13) {
        searchBoat()
    }
});

/**
 * 搜索波浪艇
 */
function searchBoat() {
    hideSubMenu();
    let value = $('.left-nav .search input').val()
    if (value) {
        $('#nav>li').each((i, ele) => {
            let boatName = $(ele).find('a').find('cite').html();
            if (boatName.includes(value)) {
                $(ele).show()
            } else {
                $(ele).hide()
            }
        })
    } else {
        $('#nav>li').show();
    }
}

/**
 * 生成左侧波浪艇ui
 */
function generateBoatNavUI(boats) {
    let nav = $('#nav')
    nav.html('')
    for (let i = 0; i < boats.length; i++) {
        let boat = boats[i]
        let submenu = '<ul class="sub-menu">';
        if (boat.deviceList == null) boat.deviceList = []
        for (let j = 0; j < boat.deviceList.length; j++) {
            let device = boat.deviceList[j]
            submenu += `
              <li >
                <a _href="/map/device" data-name="${device.name}"data-type="${device.type}">
                    <cite class="status-${getColorByStatus(device.status)}">
                      <i class="fa fa-desktop"></i>
                        ${device.name}
                    </cite>
                </a>
            </li>
            `
        }
        submenu += '</ul>'

        let html = `
         <li data-name="${boat.name}" data-code="${boat.code}" data-id="${boat.id}">
                <a href="javascript:;">
                    <cite class="status-${getColorByStatus(boat.status)}">
<!--                        <i class="fa fa-ship"></i>-->
                        <img src="/img/icon/boat_icon.png" style="width: 40px;height: 40px">
                        ${boat.name} ${boat.code}
                    </cite>
                    <i class="fa fa-angle-left"></i>
                </a>
                ${submenu}
            </li>`;
        nav.html(nav.html() + html);
    }
    registerNavEvent()
}

/**
 * 根据状态标志获取颜色 0 green 1 yellow 2 red
 * @param {number} status
 */
function getColorByStatus(status) {
    if (status === 0) return 'green';
    if (status === 1) return 'yellow';
    if (status === 2) return 'red';
}

/**
 * 获取载荷开关颜色
 * @param state
 * @returns {string}
 */
function getLoadColor(state) {
    if (state == 0) return 'yellow';
    if (state == 1) return 'green';
}

// 左侧菜单效果 end

// 波浪艇悬浮窗口
/**
 * 显示波浪艇的信息窗口
 * @param boat class
 * @param top 离窗口上方的px
 * @param left 离窗口左边的px
 */
function showBoatInfo(boat, top = 400, left = 400) {
    // 填写信息
    let keys = ['name', 'code', 'bdMode', 'card', 'lifeSpan', 'maintainOrg', 'launchDate']
    for (let key of keys) {
        if (boat[key] !== 'undefined') {
            let value = boat[key];
            if (key === 'bdMode') {
                if (value === 0) value = '北斗二代'
                if (value === 1) value = '北斗三代'
                if (value === 2) value = '天通'
            }
            $('.boat-' + key).html(value);
        }
    }
    if (boat.dept.deptName) $('.boat-dept').html(boat.dept.deptName);

    if (boat.statusList || boat.statusList.length !== 0) {
        let status = boat.statusList[boat.statusList.length - 1]
        $('.boat-lng').html(toDegrees(status.lng));
        $('.boat-lat').html(toDegrees(status.lat));
        let updateTime = status.time
        if (updateTime instanceof Date) {
            updateTime = updateTime.Format('yyyy-MM-dd HH:mm:ss')
        }
        $('.boat-updateTime').html(updateTime);
    }

    if (boat.img) {
        $('.boat-img').attr('src', '/boat/boat/img/' + boat.id);
        $('.boat-img').show();
    } else {
        $('.boat-img').hide();
    }

    // 计算宽度和长度
    let width = boatInfoDiv.width();
    let height = boatInfoDiv.height();

    let screenWidth = $(window).width() - (rightDivShown ? rightDivWidth + intervalWidth : 0);
    let screenHeight = $(window).height();

    if (left < leftDivWidth + intervalWidth) {
        left = leftDivWidth + intervalWidth;
    }

    if (width + left > screenWidth - intervalWidth) {
        left = screenWidth - intervalWidth - width;
    }

    if (top < headDivHeight + intervalWidth) {
        top = headDivHeight + intervalWidth;
    }

    if (height + top > screenHeight - intervalWidth) {
        top = screenHeight - intervalWidth - height;
    }

    boatInfoDiv.css({left, top})

    boatInfoDiv.fadeIn(animateTime.boatInfo);
}

function hideBoatInfo() {
    boatInfoDiv.fadeOut(animateTime.boatInfo);
}

$(document).keydown(function (e) {
    console.log(e.keyCode)
    if (e.keyCode === 81) { // q
        showBoatInfo(boats[0], mouseY, mouseX);
    } else if (e.keyCode === 87) { // w
        hideBoatInfo();
    } else if (e.keyCode === 69) {//e
        showBoatInfo(boats[1], mouseY, mouseX);
    }
})

let mouseX = 0, mouseY = 0;
$(document).mousemove(function (event) {
    mouseX = event.pageX;
    mouseY = event.pageY;
});
// for test end

// 波浪艇悬浮窗口 end

// 右侧状态窗口按钮

$('#load-btn').click(() => {
    if ($('#load-panel').css('display') === 'none') {
        showLoadPanel();
    } else {
        hideLoadPanel();
    }
})

$('#route-btn').click(function () {
    if (middleRouteCode === rightDivCode) return
    middleRouteCode = rightDivCode;
    $('.sub-menu li a').removeClass('selected');
    let boat = getBoatByCode(rightDivCode);
    if (boat) showMiddle(`${boat.name} ${boat.code} 轨迹查询`, "/map/route?boatId=" + boat.id, 1);
})

function showLoadPanel() {
    $('#value-panel').slideUp();
    $('#load-panel').slideDown();

    var boat = getBoatByCode(rightDivCode)
    /*if (boat && boat.rtsp) {
        player = new window.Player({
            lang: 'zh',
            id: 'mse',
            height: '100%',
            width: '100%',
            isLive: true,
            playsinline: true,
            url: 'http://localhost:8866/live?url=' + boat.rtsp,
            autoplay: true,
            autoplayMuted: true,
            plugins: [window.FlvPlayer],
            playbackRate: [],
            volume: 0.5,
            // pip: true,
            closeVideoClick: true,
            closeVideoDblclick: true,
            closeVideoTouch: true
        });
    }*/

}

function hideLoadPanel() {
    $('#value-panel').slideDown()
    $('#load-panel').slideUp()
    //if (player) player.destroy();
}

let btnLoading = $(' <i class="layui-layer-loading-icon layui-icon layui-icon-loading-1 layui-anim layui-anim-rotate layui-anim-loop" style="display: none"></i>')

/**
 * 点击模式开关后发送切换模式请求
 */
$('#switch').change(function (event) {
    let mode = $(this).is(':checked') ? 1 : 0
    let name = getBoatByCode(rightDivCode).name
    showSwitchLoading();
    fetch('/cmd/ctrl', {
        method: 'post',
        body: JSON.stringify({
            code: rightDivCode,
            key: 'mode',
            value: mode,
        }),
        headers: {
            'Content-Type': 'application/json;charset=UTF-8',
        }
    }).then(function (res) {
        hideSwitchLoading();
        if (res.redirected) {
            if (res.url.includes('login')) {
                alert('登录状态失效，请重新登录')
            }
            window.location.replace(res.url)
        } else if (res.status === 200) {
            layer.msg(`${name}${rightDivCode} 模式切换已发送`, {icon: 1})
            $('#controlMode').html(mode ? '自动' : '手动')
        } else {
            layer.msg(`${name}${rightDivCode} 模式切换发送失败`, {icon: 2})
            $(this).prop('checked', mode !== 1)
        }
    }).catch((reason) => {
        hideSwitchLoading();
        layer.msg(`网络连接失败`, {icon: 2})
    })
})

function showSwitchLoading() {
    let input = $('#switch')
    let span = input.parent().parent().parent().find('.val').find('span')
    span.parent().append(btnLoading)
    btnLoading.show();
    span.hide();
    input.attr("disabled", "")
}

function hideSwitchLoading() {
    let input = $('#switch')
    let span = input.parent().parent().parent().find('.val').find('span')
    btnLoading.hide();
    btnLoading.remove();
    span.show();
    input.removeAttr("disabled")
}

$('#angle-btn').click(function () {
    let value = $('input[name=rudderAngle]').val();
    if (value === 'undefined' || value === '') {
        layer.msg('请填写舵角值', {icon: 7})
        return;
    }
    showAngleLoading();
    let name = getBoatByCode(rightDivCode).name
    fetch('/cmd/ctrl', {
        method: 'post',
        body: JSON.stringify({
            code: rightDivCode,
            key: 'angle',
            value: value,
        }),
        headers: {
            'Content-Type': 'application/json;charset=UTF-8',
        }
    }).then(function (res) {
        hideAngleLoading();
        if (res.redirected) {
            if (res.url.includes('login')) {
                alert('登录状态失效，请重新登录')
            }
            window.location.replace(res.url)
        } else if (res.status === 200) {
            layer.msg(`${name}${rightDivCode} 舵角控制已发送`, {icon: 1})
        } else {
            layer.msg(`${name}${rightDivCode} 舵角控制发送失败`, {icon: 2})
        }
    }).catch((reason) => {
        hideAngleLoading();
        layer.msg(`网络连接失败`, {icon: 2})
    })
})

function redirectResponse(response) {
    // 302 响应会在这里处理
    console.log("302 Found - Redirection detected");

    // 获取重定向地址
    var redirectUrl = response.getResponseHeader('Location');
    console.log('Redirect URL:', redirectUrl);
    alert("登录状态失效，请重新登录")

    // 手动处理重定向，您可以使用 window.location.href 或其他方法来跳转
    window.location.href = redirectUrl;
}

function showAngleLoading() {
    let btn = $('#angle-btn')
    btn.parent().append(btnLoading)
    btnLoading.show();
    btn.hide();
}

function hideAngleLoading() {
    let btn = $('#angle-btn')
    btnLoading.hide();
    btnLoading.remove();
    btn.show();
}


// 右侧状态窗口按钮 end